import Player from "../Map/Player";

const {ccclass, property} = cc._decorator;

@ccclass
export default class DirController extends cc.Component {
    private point:cc.Node
    /** 方向盘操作的目标 */
    target:Player;
    /** 当前方向 */
    private dir:QM.Dir=0;
    /** 是否移动 */
    private isMove:boolean=false;
    
    onLoad(){
        this.point = this.node.getChildByName("point");
        this.node.on(cc.Node.EventType.TOUCH_MOVE,this.Move,this);
        this.node.on(cc.Node.EventType.TOUCH_START,this.Move,this);
        this.node.on(cc.Node.EventType.TOUCH_END,this.Stop,this);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL,this.Stop,this);
    }


    update(){
        if(!this.isMove || !this.target) return;
        this.target.move(this.dir);
        if(this.dir==0){
            this.isMove = false;
        }
    }
  

    Move(event:cc.Event.EventTouch){
        
        var p = cc.v2(this.node.convertToNodeSpaceAR(event.getLocation()));         
        if(p.mag()< (this.node.width -this.point.width) /2){          
            this.point.position = p;                
        }           
        if(this.target){
            
            var angle = cc.v2(1,0).signAngle(this.point.position)*180/Math.PI;            
            var dir = QM.getDirForAngle(angle);                        
            this.dir = dir;
            this.isMove = true;
        }
        
    }

    Stop(){
        this.point.position = cc.Vec2.ZERO;
        this.dir = 0;        
    }

    onEnable(){
        this.Stop();
    }
}
